package cn.s1995.sloth.bms.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.s1995.sloth.bizs.entity.*;
import cn.s1995.sloth.bizs.entity.base.BaseEntity;
import cn.s1995.sloth.bizs.oo.req.ProdREQ;
import cn.s1995.sloth.bizs.oo.vo.BmsProdVO;
import cn.s1995.sloth.bizs.oo.vo.ProdVO;
import cn.s1995.sloth.bizs.oo.vo.excel.ProdExcelVO;
import cn.s1995.sloth.bizs.service.CartService;
import cn.s1995.sloth.bizs.service.ProdGroupReferenceService;
import cn.s1995.sloth.bizs.service.ProdService;
import cn.s1995.sloth.bizs.service.SkuService;
import cn.s1995.sloth.common.core.util.R;
import cn.s1995.sloth.common.excel.annotation.ResponseExcel;
import cn.s1995.sloth.common.log.annotation.SysLog;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 产品
 *
 * @author Lex
 * @date 2023-12-14 10:02:00
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/prod")
@Tag(description = "Prod", name = "BMS-产品管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class ProdController {

    private final ProdService prodService;
    private final SkuService skuService;
    private final CartService cartService;
    private final ProdGroupReferenceService prodGroupReferenceService;

    /**
     * 分页查询
     *
     * @param page 分页对象
     * @param req  产品
     * @return
     */
    @ApiOperationSupport(order = 1)
    @Operation(summary = "分页查询", description = "分页查询")
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('bizs_Prod_view')")
    public R getPage(@ParameterObject Page page, @ParameterObject Prod req) {
    	return R.ok(prodService.selectJoinListPage(page, BmsProdVO.class, buildQueryWrapper(req)));
    }


    /**
     * 列表查询
     *
     * @param req 产品
     * @return
     */
    @ApiOperationSupport(order = 1)
    @Operation(summary = "列表查询", description = "列表查询")
    @GetMapping("/list")
    // @PreAuthorize("@pms.hasPermission('bizs_Prod_view')")
    public R<List<BmsProdVO>> getList(@ParameterObject Prod req) {
    	return R.ok(prodService.selectJoinList(BmsProdVO.class, buildQueryWrapper(req)));
    }


    /**
     * 通过id查询产品
     *
     * @param id id
     * @return R
     */
    @ApiOperationSupport(order = 1)
    @Operation(summary = "通过id查询", description = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('bizs_Prod_view')")
    public R<ProdVO> getById(@PathVariable("id") Long id) {
        Prod one = prodService.getById(id);
        ProdVO vo = BeanUtil.copyProperties(one, ProdVO.class);
        // 设置sku
        vo.setSkuList(
                skuService.list(
                        Wrappers.lambdaQuery(Sku.class)
                                .eq(Sku::getProdId, vo.getId())
                                .eq(Sku::getIsDeleted, Boolean.FALSE)
                )
        );
        vo.setGroupList(
                prodGroupReferenceService.list(
                        Wrappers.lambdaQuery(ProdGroupReference.class)
                                .eq(ProdGroupReference::getProdId, vo.getId())
                ).stream().map(ProdGroupReference::getGroupId).toList()
        );
        return R.ok(vo);
    }

    /**
     * 新增产品
     *
     * @param req 产品
     * @return R
     */
    @ApiOperationSupport(order = 10)
    @Operation(summary = "新增产品", description = "新增产品")
    @SysLog("新增产品")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('bizs_Prod_add')")
    public R save(@Validated(BaseEntity.ValidGroup.Add.class) @RequestBody ProdREQ req) {
        prodService.saveProd(req);
        return R.ok();
    }

    /**
     * 修改产品
     *
     * @param req 产品
     * @return R
     */
    @ApiOperationSupport(order = 20)
    @Operation(summary = "修改产品", description = "修改产品")
    @SysLog("修改产品")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('bizs_Prod_edit')")
    public R updateById(@Validated(BaseEntity.ValidGroup.Edit.class) @RequestBody ProdREQ req) {
        prodService.updateProd(req);

        removeProdAssociationCache(CollUtil.toList(req.getId()));

        return R.ok();
    }

    /**
     * 通过id删除产品
     *
     * @param ids id列表
     * @return R
     */
    @ApiOperationSupport(order = 30)
    @Operation(summary = "通过id删除产品", description = "通过id删除产品")
    @SysLog("通过id删除产品")
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('bizs_Prod_del')")
    public R removeById(@RequestBody Long[] ids) {
        ArrayList<Long> prodIds = CollUtil.toList(ids);

        for (Long prodId : prodIds) {
            prodService.removeProd(prodId);
        }

        removeProdAssociationCache(prodIds);

        return R.ok();
    }


    /**
     * 导出excel 表格
     *
     * @param req 查询条件
     * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ApiOperationSupport(order = 40)
    @Operation(summary = "导出excel表格", description = "")
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('bizs_Prod_export')")
    public List<ProdExcelVO> export(Prod req, Long[] ids) {
        return prodService
                .list(Wrappers.lambdaQuery(req).in(ArrayUtil.isNotEmpty(ids), Prod::getId, ids))
                .stream().map(o -> BeanUtil.copyProperties(o, ProdExcelVO.class)).toList();
    }

    /**
     * 更新产品状态-上架|下架
     */
    @ApiOperationSupport(order = 41)
    @Operation(summary = "更新产品状态-上架|下架", description = "更新产品状态-上架|下架")
    @SysLog("更新产品状态-上架|下架")
    @PutMapping("/{id}/sale")
    @PreAuthorize("@pms.hasPermission('bizs_Prod_edit')")
    public R putSale(@PathVariable Long id, @RequestParam Boolean state) {
        prodService.update(
                Wrappers.lambdaUpdate(Prod.class)
                        .eq(Prod::getId, id)
                        .set(Prod::getIsSale, state)
        );

        prodService.removeProductCacheByProdId(id);

        removeProdAssociationCartCache(CollUtil.toList(id));

        return R.ok();
    }

    /**
     * 更新产品状态-推荐
     */
    @ApiOperationSupport(order = 41)
    @Operation(summary = "更新产品状态-推荐", description = "更新产品状态-推荐")
    @SysLog("更新产品状态-推荐")
    @PutMapping("/{id}/recommend")
    @PreAuthorize("@pms.hasPermission('bizs_Prod_edit')")
    public R putRecommend(@PathVariable Long id, @RequestParam Boolean state) {
        prodService.update(
                Wrappers.lambdaUpdate(Prod.class)
                        .eq(Prod::getId, id)
                        .set(Prod::getIsRecommend, state)
        );

        return R.ok();
    }


    /**
     * 移除购物车缓存
     *
     * @param prodIds
     */
    private void removeProdAssociationCartCache(List<Long> prodIds) {
        // 获取购物车中拥有某件产品的用户，用于清除该用户购物车的缓存
        List<Long> uidList = cartService.list(
                Wrappers.lambdaQuery(Cart.class)
                        .select(Cart::getUid)
                        .in(Cart::getProdId, prodIds)
        ).stream().map(Cart::getUid).toList();
        // 删除购物车缓存
        for (Long uid : uidList) {
            cartService.removeShopCartItemsCacheByUserId(uid);
        }
    }

    /**
     * 移除sku缓存
     *
     * @param prodIds
     */
    private void removeProdAssociationSkuCache(List<Long> prodIds) {
        List<Sku> originSkuList = skuService.list(
                Wrappers.lambdaQuery(Sku.class)
                        .select(Sku::getId, Sku::getProdId)
                        .in(Sku::getProdId, prodIds)
        );
        // 删除sku缓存
        for (Sku sku : originSkuList) {
            skuService.removeSkuCacheBySkuId(sku.getId(), sku.getProdId());
        }
    }

    /**
     * 移除产品关联缓存
     *
     * @param prodIds
     */
    private void removeProdAssociationCache(List<Long> prodIds) {
        removeProdAssociationCartCache(prodIds);
        removeProdAssociationSkuCache(prodIds);
    }

    /**
     * 构建查询条件
     * @param req
     * @return
     */
    @NotNull
    private static MPJLambdaWrapper<Prod> buildQueryWrapper(Prod req) {
    	MPJLambdaWrapper<Prod> wrapper = new MPJLambdaWrapper<Prod>();
        wrapper.eq(Objects.nonNull(req.getShopId()), Prod::getShopId, req.getShopId());
        wrapper.like(Objects.nonNull(req.getCategoryId()), Prod::getCategoryPath, req.getCategoryId());
        wrapper.eq(Objects.nonNull(req.getIsSale()), Prod::getIsSale, req.getIsSale());
        wrapper.eq(Objects.nonNull(req.getIsCustomizable()), Prod::getIsCustomizable, req.getIsCustomizable());
        wrapper.eq(Objects.nonNull(req.getIsRecommend()), Prod::getIsRecommend, req.getIsRecommend());
        wrapper.eq(Objects.nonNull(req.getIsHot()), Prod::getIsHot, req.getIsHot());

        wrapper.and(
                StrUtil.isNotEmpty(req.getSearch()),
                w -> w.like(Prod::getId, req.getSearch())
                        .or()
                        .like(Prod::getName, req.getSearch())
                        .or()
                        .like(Prod::getBrief, req.getSearch())
                        .or()
                        .like(Prod::getSn, req.getSearch())
                        .or()
                        .like(Prod::getModel, req.getSearch())
        );
        //关联查询店铺名称
        wrapper.selectAll(Prod.class)
                .selectAs(Shop::getName, BmsProdVO::getShopName)
                .selectAs(ProdCategory::getName, BmsProdVO::getCategoryName)
                .leftJoin(Shop.class, Shop::getId, Prod::getShopId)
                .leftJoin(ProdCategory.class, ProdCategory::getId, Prod::getCategoryId);
        return wrapper;
    }
}
